package ink.tiptop.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhongjiafeng
 */
@Component("simpleServiceFactory")
@Slf4j
public class SimpleServiceFactory<V> implements InitializingBean {

    private ConcurrentHashMap<Enum, V> serviceMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void postConstruct() {
        log.error("在init之后,执行此方法");
    }

    public V getService(Enum e) {
        if (e == null) {
            throw new RuntimeException("Enum cannot be null");
        }
        V v = serviceMap.get(e);
        if (v == null) {
            throw new RuntimeException(e + " cannot be find it's value");
        }
        return v;
    }

    public V addService(Enum e, V v) {
        if (e == null || v == null) {
            throw new RuntimeException(e + " or " + v + " cannot be null");
        }
        V v1 = serviceMap.get(e);
        if (v1 != null) {
            throw new RuntimeException(v + " already existed,no further operate");
        }
        return serviceMap.put(e, v);
    }


    /**
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.error("afterPropertiesSet");
    }
}
